package com.efounder.agency.utils;

import android.content.Context;
import android.util.Log;

import com.efounder.builder.base.data.EFDataSet;
import com.efounder.builder.base.data.EFRowSet;
import com.efounder.eai.EAI;
import com.efounder.eai.data.JParamObject;
import com.efounder.eai.data.JResponseObject;
import com.efounder.model.AgentTaskModel;
import com.efounder.util.AndroidEnvironmentVariable;
import com.efounder.util.CommonPo;
import com.efounder.util.GlobalMap;
import com.efounder.util.StorageUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 公文审批，费用报销 合同系统 获取token
 *
 * @author yqs
 */
public class TokenHelperPG {
    private static String TAG = "TokenHelper";



    /**
     * 得到token (招标使用)
     *
     * @return
     */
    public static String getZBTokenID(Context context, AgentTaskModel model) {
        String type = model.getType();
        StorageUtil storageUtil1 = new StorageUtil(context, "storage");
        String systemUserName = storageUtil1.getString("userName");
        StorageUtil storageUtil = new StorageUtil(context, systemUserName);
        String tokenId = null;
        JParamObject PO = JParamObject.Create();
        CommonPo.setPoToNull();
        JResponseObject RO = null;
        //String existToken = GlobalMap.getProperty(type + "Id", "");
        //if (existToken.equals("")) {
        Log.i(TAG, type + "开始请求tokenid--");
        String currentId = AndroidEnvironmentVariable.getUserID();
        String currentpwd = AndroidEnvironmentVariable.getPassword();

        PO.SetValueByParamName("WB_SYS_KEY", type);

        String userId = storageUtil.getString(type + "Id", "");
        String passWord = storageUtil.getString(type + "Pwd", "");
        if (!type.equals("CONTRACT") && !type.equals("FFS")
                && (userId.equals("") || passWord.equals(""))) {
            Log.i(TAG, type + "帐号密码不存在，停止请求tokenid--");
            return null;
        }

        // 设置合同PO
        if (type.equals("CONTRACT")) {// 合同
            PO.SetValueByParamName("CONTRACT" + "_params_userid", currentId);
            PO.SetValueByParamName("CONTRACT" + "_params_pwd", currentpwd);
            PO.SetValueByParamName("CONTRACT" + "_systemmethod",
                    "GetTokenID");
        } else if (type.equals("FFS")) {// 费用报销
            PO.SetValueByParamName("FFS_params_loginname", currentId);
            PO.SetValueByParamName("FFS_params_password", currentpwd);
            PO.SetValueByParamName("FFS_systemmethod", "GetTokenID");
        } else if (type.equals("PGZB")) {// 招标管理系统

//            PO.SetValueByParamName("PGZB_systemmethod", "GetTokenID");
//            PO.SetValueByParamName("PGZB_params_Userid", userId);
//            PO.SetValueByParamName("PGZB_params_Pwd", passWord);


//				EAI.Protocol = "http";
//				EAI.Server = "192.168.191.1";
//				 //EAI.Server = "192.168.253.6";
//				EAI.Port = "8080";
//				EAI.Path = "fmis";
//				EAI.Service = "Android";
				PO.SetValueByParamName("PGZB_systemmethod", "GetTokenIDNew");
				PO.SetValueByParamName("PGZB_params_Userid", userId);
				PO.SetValueByParamName("PGZB_params_Pwd",passWord);
				PO.SetValueByParamName("PGZB_params_spflag", "");
				PO.SetValueByParamName("PGZB_params_dataflag", "A");
        } else {// OA
            PO.SetValueByParamName(type + "_params_userid", userId);
            PO.SetValueByParamName(type + "_params_pwd", passWord);
            PO.SetValueByParamName(type + "_systemmethod", "GetTokenID");
        }

        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (RO != null) {
            Map<String, Object> tokenMap = RO.getResponseMap();

            String token = getTokenFromMap(tokenMap, model);
            //UnReadCount
            GlobalMap.setProperty(type + "Id", token);
            System.out.println("服务器获取的" + type + "tokenId:" + token);
            return token;
        }

        return "";
        //  } else {
        //   Log.i(TAG, type + "token已存在");
        //     return existToken;
        // }

    }

    /**
     * 从map中获得tokenid
     *
     * @param map
     * @param model
     * @return
     */
    private static String getTokenFromMap(Map<String, Object> map, AgentTaskModel model) {
        String token = "";
        EFDataSet dataSet = (EFDataSet) map.get(model.getType());
        if (dataSet == null) {
            return token;
        }
        List<EFRowSet> rowSets = dataSet.getRowSetArray();
        if (rowSets == null) {
            return token;
        }
        if (rowSets.size() <= 0) {
            return token;
        }
        EFRowSet efORowSet = (EFRowSet) rowSets.get(0);
        token = (String) efORowSet.getDataMap().get("TokenID");
        if (efORowSet.hasKey("UnReadCount")) {
            if (!"".equals(efORowSet.getString("UnReadCount", "0"))) {
                model.setDbCount(Integer.valueOf(efORowSet.getString("UnReadCount", "")));
            }
        }
        return token;

    }

    /**
     * 请求未读数量以及token
     *
     * @param modellist
     * @param context
     */
    public static void getTokenAndUnreadCount(List<AgentTaskModel> modellist,
                                              Context context) {

        // EAI.Protocol = "http";
        // // EAI.Server = "192.168.252.1";
        // EAI.Server = "192.168.0.134";
        // EAI.Port = "8080";
        // EAI.Path = "ESTMobile";
        // EAI.Service = "Android";

        StorageUtil storageUtil1 = new StorageUtil(context, "storage");
        String systemUserName = storageUtil1.getString("userName");
        StorageUtil storageUtil = new StorageUtil(context, systemUserName);
        long time = System.currentTimeMillis();
        List<AgentTaskModel> list = new ArrayList<AgentTaskModel>();
        JParamObject PO = JParamObject.Create();
        CommonPo.setPoToNull();
        JResponseObject RO = null;
        String currentId = AndroidEnvironmentVariable.getUserID();
        String currentpwd = AndroidEnvironmentVariable.getPassword();
        Iterator<AgentTaskModel> iterator = modellist.iterator();
        System.out.println(list.size());

        while (iterator.hasNext()) {
            boolean needDelete = false;
            AgentTaskModel model = iterator.next();

            String existToken = GlobalMap.getProperty(model.getType() + "Id",
                    "");
            String userId = storageUtil.getString(model.getType() + "Id", "");
            String passWord = storageUtil
                    .getString(model.getType() + "Pwd", "");
            if (!model.getType().equals("CONTRACT")
                    && !model.getType().equals("FFS")
                    && (userId.equals("") || passWord.equals(""))) {
                needDelete = true;
            }
            if (!needDelete) {
                list.add(model);
            }

        }
        System.out.println(list.size());
        String systemTypeString = "";
        if (list.size() == 0) {
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            AgentTaskModel model = list.get(i);
            systemTypeString = systemTypeString + model.getType() + ",";
            if (model.getType().equals("CONTRACT")) {// 合同
                PO.SetValueByParamName("CONTRACT" + "_params_userid", currentId);
                PO.SetValueByParamName("CONTRACT" + "_params_pwd", currentpwd);
                PO.SetValueByParamName("CONTRACT" + "_systemmethod",
                        "GetApprovalTabsCountHandler");
            } else if (model.getType().equals("FFS")) {// 费用报销
                PO.SetValueByParamName("FFS" + "_params_loginname", currentId);
                PO.SetValueByParamName("FFS" + "_params_password", currentpwd);
                PO.SetValueByParamName("FFS" + "_systemmethod",
                        "GetTabsCountHandler");
            } else {
                String userId = storageUtil.getString(model.getType() + "Id",
                        "");
                String passWord = storageUtil.getString(
                        model.getType() + "Pwd", "");
                PO.SetValueByParamName(model.getType() + "_params_userid",
                        userId);
                PO.SetValueByParamName(model.getType() + "_params_pwd",
                        passWord);
                PO.SetValueByParamName(model.getType() + "_systemmethod",
                        "GetTabsCountHandler");
            }
        }

        systemTypeString = systemTypeString.substring(0,
                systemTypeString.length() - 1);
        PO.SetValueByParamName("WB_SYS_KEY", systemTypeString);
        try {
            // 连接服务器
            RO = EAI.DAL.SVR("ExternalInterfaceDataService", PO);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (RO != null) {
            Map<String, Object> map = RO.getResponseMap();
            if (map == null) {
                return;
            }
            for (String key : map.keySet()) {
                if (key.equals("Authorization")) {
                    continue;
                }
                EFDataSet dataSet = (EFDataSet) map.get(key);
                if (dataSet == null) {
                    continue;
                }
                List<EFRowSet> rowSets = dataSet.getRowSetArray();
                if (rowSets == null) {
                    continue;
                }
                if (rowSets.size() <= 0) {
                    continue;
                }
                EFRowSet efORowSet = (EFRowSet) rowSets.get(0);
                if (efORowSet.hasKey("TokenID")) {
                    String token = (String) efORowSet.getDataMap().get(
                            "TokenID");
                    // System.out.println(key + "系统获取token值:" + token);
                    GlobalMap.setProperty(key + "Id", token);
                    System.out.println(key + "系统获取token值:"
                            + GlobalMap.getProperty(key + "Id", ""));
                }

                // 未读数量
                EFRowSet tempRowSet = (EFRowSet) rowSets.get(1);
                if (tempRowSet == null) {
                    continue;
                }
                Map<String, EFDataSet> dataMap = tempRowSet.getDataSetMap();
                EFDataSet efDataSet2 = (EFDataSet) dataMap.get("_CDS_");
                List<EFRowSet> efRowSets = (List<EFRowSet>) efDataSet2
                        .getRowSetArray();
                for (int j = 0; j < efRowSets.size(); j++) {
                    EFRowSet efRowSet2 = (EFRowSet) efRowSets.get(j);
                    setCount(modellist, key, efRowSet2);

                }

            }

        }
        System.out.println("---加载token和未读数量所需时间--"
                + (System.currentTimeMillis() - time));
    }

    /**
     * @param list
     * @param key
     */
    public static void setCount(List<AgentTaskModel> list, String key,
                                EFRowSet efRowSet) {
        for (int i = 0; i < list.size(); i++) {
            AgentTaskModel model = list.get(i);
            String count = efRowSet.getString("count", "0");
            if ("".equals(count)) {
                count = "0";
            }
            if (key.equals(model.getType())) {
                if (efRowSet.getString("id", "").equals("db")
                        || efRowSet.getString("id", "").equals("0")) {
                    model.setDbCount(Integer.valueOf(count));
                } else if (efRowSet.getString("id", "").equals("dy")
                        || efRowSet.getString("id", "").equals("1")) {
                    model.setDyCount(Integer.valueOf(count));
                } else if (efRowSet.getString("id", "").equals("bl")) {
                    model.setDyCount(Integer.valueOf(count));
                }
            }
        }
    }

    public static String getOneToken(String type, Context context) {
        String token = "";
        if (!GlobalMap.getProperty(type + "Id", "").equals("")) {
            token = GlobalMap.getProperty(type + "Id", "");
            System.out.println("----" + type + "token存在--");

        } else {
            System.out.println("----" + type + "token不存在--");
            AgentTaskModel model = new AgentTaskModel();
            model.setType(type);
            List<AgentTaskModel> list = new ArrayList<AgentTaskModel>();
            list.add(model);
            getTokenAndUnreadCount(list, context);
            token = GlobalMap.getProperty(type + "Id", "");
        }
        return token;

    }
}
